package com.ynet.middleground.riskmanage.model;

import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ynet.core.common.BaseReqObj;
import com.ynet.core.exception.BusinessException;
import com.ynet.host.HostConstants;
import com.ynet.middleground.riskmanage.bean.PurchaseReq;
import com.ynet.middleground.riskmanage.dto.*;
import com.ynet.middleground.riskmanage.entity.*;
import com.ynet.middleground.riskmanage.external.MainBusinessConfig;
import com.ynet.middleground.riskmanage.external.purchasecenter.ReqTypeEnum;
import com.ynet.middleground.riskmanage.utils.ApiUtil;
import com.ynet.middleground.riskmanage.utils.BeanUtil;
import com.ynet.middleground.riskmanage.utils.DateUtils;

/**
 * @ClassName PurchaseCenterModel
 * @Description 对接采购中心服务处理流程
 * @Author zhangyongbin
 * @Date 2020/8/13 14:55
 * @Version 1.0
 */
@Component
public class PurchaseCenterModel {
    /**
     * 调用成功标识
     **/
    private static final String SUCCESS = "0";

    /**
     * 日志打印时显示的名称
     */
    public static final String LOG_NAME = "采购中心";

    // /**
    // * 采购中心分配给金控中台的账号
    // */
    // private static final String ACCOUNT_NUM = "ceshi123";

    @Autowired
    MainBusinessConfig config;

    @Autowired
    private ApiUtil apiUtil;

    @Autowired
    private Mapper mapper;

    @Autowired
    private OrderInfoModel purchaseOrderInfoMapper;

    @Autowired
    OrderInfoHistoryModel purchaseOrderInfoHistoryMapper;

    @Autowired
    InvoiceInfoModel purchaseInvoiceInfoMapper;

    @Autowired
    InvoiceInfoHistoryModel purchaseInvoiceHistoryInfoMapper;

    @Autowired
    private ReconciliationHistoryModel reconciliationHistoryModel;

    @Autowired
    private ReconciliationModel reconciliationModel;

    @Autowired
    private MainBusinessConfig mainBusinessConfig;

    /**
     * @Description 获取订单信息
     * @Date 15:32 2020/8/13
     * @Param [req]获取订单信息服务请求信息
     * @return java.util.List<com.ynet.middleground.riskmanage.dto.PurchaseOrderDataDTO>
     **/
    @Transactional(rollbackFor = Exception.class)
    public PurchaseOrderDTO getOrderData(PurchaseReq req) {
        // Add By liwq On 2021-01-27 Start
        // 增加排序功能&指定字段排序功能
        if (!StringUtils.isEmpty(req.getSortField()) && StringUtils.isEmpty(req.getSortOrder())) {
            throw new BusinessException("请上送排序方式", "DAGM0001");
        }
        if (StringUtils.isEmpty(req.getSortField()) && !StringUtils.isEmpty(req.getSortOrder())) {
            throw new BusinessException("请上送排序字段", "DAGM0002");
        }
        if (!StringUtils.isEmpty(req.getSortOrder())) {
            List<String> sortOrders = mainBusinessConfig.getSortOrder();
            if (!sortOrders.contains(req.getSortOrder())) {
                throw new BusinessException("请上送有效排序方式", "DAGM0005");
            }
        }
        if (!StringUtils.isEmpty(req.getSortField())) {
            List<String> dagangSortField = mainBusinessConfig.getPurchaseOrderSortField();
            if (dagangSortField.size() == 0) {
                throw new BusinessException("请联系管理员维护采购中心有效排序字段", "DAGM0004");
            }
            if (dagangSortField.size() > 0) {
                if (!dagangSortField.contains(req.getSortField())) {
                    throw new BusinessException("请上送有效排序字段", "DAGM0003");
                }
            }
        }
        // Add By liwq On 2021-01-27 End

        Map<String, Object> params = new HashMap<>(4);
        // 请求采购中心服务参数
        // params.put("accountnum", ACCOUNT_NUM);
        params.put("accountnum", mainBusinessConfig.getPurchaseAccount());
        params.put("companyname", req.getUserName());
        params.put("querytype", ReqTypeEnum.REQ_ORDER_TYPE.getType());
        params.put("datefromto", req.getStartorenddate());
        if (StringUtils.isNotEmpty(req.getPlanNum())) {
            params.put("plancode", req.getPlanNum());
        }
        // Add By Liwq On 2021-01-27 Start
        // 增加排序功能&指定字段排序功能
        if (!StringUtils.isEmpty(req.getSortField()) && !StringUtils.isEmpty(req.getSortOrder())) {
            params.put("sortField", req.getSortField());
            params.put("sortOrder", req.getSortOrder());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getPageNum()))) {
            params.put("pageNum", req.getPagerInfo().getPageNum());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getPageSize()))) {
            params.put("pageSize", req.getPagerInfo().getPageSize());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getTotal()))) {
            params.put("total", req.getPagerInfo().getTotal());
        }
        // Add By Liwq On 2021-01-27 End

        JSONObject apiResult = apiUtil.sendApiLog(ReqTypeEnum.REQ_ORDER_TYPE.getCode(), config.getPurchaseUrl(),
            getHeadMap(), params, HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
        // JSONObject apiResult = testOrderData();
        String code = apiResult.getString("error_code");
        String message = apiResult.getString("reason");
        if (!SUCCESS.equals(code)) {
            throw new BusinessException(message, code);
        }
        JSONObject result = apiResult.getJSONObject("result");

        Integer total = result.getInteger("total");

        // Add By Liwq On 2021-01-27 Start
        // 总条数
        req.getPagerInfo().setTotal(total);
        // Add By Liwq On 2021-01-27 End

        JSONArray items = result.getJSONArray("items");
        PurchaseOrderDTO purchaseOrderDTO = new PurchaseOrderDTO();
        purchaseOrderDTO.setTotal(total);
        if (total == 0) {
            purchaseOrderDTO.setItems(Collections.emptyList());
            return purchaseOrderDTO;
        }
        List<PurchaseOrderInfo> purchaseOrderInfoList = insertOrUpdateOrderInfo(items, req);
        List<PurchaseOrderDataDTO> purchaseOrderDataDTOList = orderDataConvert(purchaseOrderInfoList);
        purchaseOrderDTO.setItems(purchaseOrderDataDTOList);

        return purchaseOrderDTO;

    }

    /**
     * 订单实体类转DTO对象
     **/
    private List<PurchaseOrderDataDTO> orderDataConvert(List<PurchaseOrderInfo> purchaseOrderInfoList) {
        List<PurchaseOrderDataDTO> purchaseOrderDataDTOList = new ArrayList<>();

        PurchaseOrderDataDTO purchaseOrderDataDTO = null;

        for (PurchaseOrderInfo orderInfo : purchaseOrderInfoList) {
            purchaseOrderDataDTO = new PurchaseOrderDataDTO();

            purchaseOrderDataDTO.setPlatNo(orderInfo.getPlanNum()).setPlanDate(orderInfo.getPlanPeriod())
                .setSupplyUser(orderInfo.getSupplierName()).setSellNo(orderInfo.getGoodsCode())
                .setSellName(orderInfo.getGoodsName()).setSpecs(orderInfo.getSpecModel())
                .setRemark(orderInfo.getRemarks()).setJlUnit(orderInfo.getMeasurementUnit())
                .setJhAcount(String.valueOf(orderInfo.getPlanQuantity()))
                .setDdAcount(String.valueOf(orderInfo.getOrderQuantity()))
                .setYsAcount(String.valueOf(orderInfo.getAcceptQuentity()))
                .setOrderDd(String.valueOf(orderInfo.getSellingPrice()))
                .setOrderMoney(String.valueOf(orderInfo.getBillTotal())).setDeptName(orderInfo.getDepName())
                .setMoneyNo(orderInfo.getInquiryNum()).setIsBuy(orderInfo.getSureSign())
                .setPayWay(orderInfo.getPayWay()).setArriveMark(orderInfo.getOrderStatus())
                // .setArriveDate(DateUtils.asDate(orderInfo.getRequiredDeliveryDate())).setSendDate(DateUtils.asDate(orderInfo.getDeliveryDate()))
                .setArriveDate(orderInfo.getRequiredDeliveryDate()).setSendDate(orderInfo.getDeliveryDate())
                .setBeandPlace(orderInfo.getBrandOrigin()).setExpDate(orderInfo.getWarrantyPeriod())
                .setGuaDate(orderInfo.getDefectsPeriod()).setZlLevel(orderInfo.getQualityStandard())
                .setGaveqy(orderInfo.getDeliveryRegion()).setGavedd(orderInfo.getLocation())
                .setAsk(orderInfo.getApplicant()).setAskDate(orderInfo.getApplicationDate().toString())
                .setProjectNo(orderInfo.getProjectNumber()).setProjectName(orderInfo.getProjectName())
                .setUsage(orderInfo.getPlanUse()).setPlanway(orderInfo.getPlanWay())
                .setPlanHead(orderInfo.getTargetSign()).setContractNo(orderInfo.getContractNum())
                .setLbNo(orderInfo.getGoodsCategoryCode()).setLbName(orderInfo.getGoodsCategoryName())
                .setOrderRes(orderInfo.getProblemSign()).setOrderStat(orderInfo.getFixedAssets())
                .setCreatDate(orderInfo.getCreateTime().toString()).setZbUser(orderInfo.getBuyer())
                .setCgPat(orderInfo.getBuyWay()).setPbUser(orderInfo.getCalibrationPerson());

            purchaseOrderDataDTOList.add(purchaseOrderDataDTO);
        }

        return purchaseOrderDataDTOList;
    }

    /**
     * 订单信息入库操作
     **/
    @Transactional(rollbackFor = Exception.class)
    public List<PurchaseOrderInfo> insertOrUpdateOrderInfo(JSONArray items, PurchaseReq req) {
        List<PurchaseOrderInfo> purchaseOrderInfoList = items.toJavaList(PurchaseOrderInfo.class);

        for (PurchaseOrderInfo purchaseOrderInfo : purchaseOrderInfoList) {
            BeanUtil.setGenericInfo(purchaseOrderInfo, req);
        }

        List<PurchaseOrderHistoryInfo> purchaseOrderHistoryInfoList = items.toJavaList(PurchaseOrderHistoryInfo.class);

        // 获取返回数据中的计划编号
        List<String> planNumList = new ArrayList<>();

        // 订单信息存入历史表
        for (PurchaseOrderHistoryInfo purchaseOrderHistoryInfo : purchaseOrderHistoryInfoList) {
            BeanUtil.setGenericInfo(purchaseOrderHistoryInfo, req);
            planNumList.add(purchaseOrderHistoryInfo.getPlanNum());
        }
        purchaseOrderInfoHistoryMapper.saveBatch(purchaseOrderHistoryInfoList);

        // 查询订单表信息数据查询条件
        QueryWrapper<PurchaseOrderInfo> queryWrapper = new QueryWrapper<PurchaseOrderInfo>();
        queryWrapper.in("plan_num", planNumList.toArray());

        // 根据计划编号查询订单信息表数据
        List<PurchaseOrderInfo> purchaseOrderInfoOldList = purchaseOrderInfoMapper.list(queryWrapper);

        // 新增数据集合
        List<PurchaseOrderInfo> purchaseOrderInfoInsertList = new ArrayList<>();

        // 更新数据集合
        List<PurchaseOrderInfo> purchaseOrderInfoUpdateList = new ArrayList<>();

        // 判断订单是否存在，存在更新，不存在新增
        boolean flag = false;
        Integer id = 0;
        for (PurchaseOrderInfo purchaseOrderInfo : purchaseOrderInfoList) {
            for (PurchaseOrderInfo purchaseOrderOldInfo : purchaseOrderInfoOldList) {
                if (purchaseOrderInfo.getPlanNum().equals(purchaseOrderOldInfo.getPlanNum())) {
                    flag = true;
                    id = purchaseOrderOldInfo.getId();
                    break;
                }
            }
            if (flag == true) {// 存在
                purchaseOrderInfo.setId(id);
                purchaseOrderInfoUpdateList.add(purchaseOrderInfo);
            } else {// 不存在
                purchaseOrderInfoInsertList.add(purchaseOrderInfo);
            }
        }

        purchaseOrderInfoMapper.saveBatch(purchaseOrderInfoInsertList);

        if (!purchaseOrderInfoUpdateList.isEmpty()) {
            purchaseOrderInfoMapper.updateBatchById(purchaseOrderInfoUpdateList);
        }
        return purchaseOrderInfoList;
    }

    /**
     * 设置请求header数据
     **/
    private Map<String, String> getHeadMap() {

        return null;
    }

    /**
     * TODO: 测试专用 测试对账单，模拟返回数据
     *
     * @return 模拟对账单数据
     * @author liulx
     * @date 2020-08-13 20:52:43
     */
    public JSONObject testReconciliationsData() {
        String testData =
            "{\"result\":{\"total\":10,\"items\":[{\"checkId\":\"testId001\",\"checkYear\":\"123444\",\"balanYear\":\"123444\",\"reviceNo\":\"123444\",\"checkFlag\":\"123444\",\"checkAudFlag\":\"123444\",\"accept\":\"123444\",\"receivePay\":\"123444\",\"checkDate\":\"2020-08-13\",\"planNo\":\"123444\",\"sellName\":\"123444\",\"specs\":\"123444\",\"unit\":\"123444\",\"orderMoney\":\"123444\",\"sendAmount\":\"123444\",\"recAmount\":\"123444\",\"balAmount\":\"123444\",\"billMoney\":\"123444\",\"checkUnit\":\"123444\",\"useUnit\":\"123444\",\"useDept\":\"123444\",\"mark\":\"123444\",\"contrackNo\":\"123444\",\"recDate\":\"2020-08-13\"},{\"checkId\":\"testId002\",\"checkYear\":\"123444\",\"balanYear\":\"123444\",\"reviceNo\":\"123444\",\"checkFlag\":\"123444\",\"checkAudFlag\":\"123444\",\"accept\":\"123444\",\"receivePay\":\"123444\",\"checkDate\":\"2020-08-13\",\"planNo\":\"123444\",\"sellName\":\"123444\",\"specs\":\"123444\",\"unit\":\"123444\",\"orderMoney\":\"123444\",\"sendAmount\":\"123444\",\"recAmount\":\"123444\",\"balAmount\":\"123444\",\"billMoney\":\"123444\",\"checkUnit\":\"123444\",\"useUnit\":\"123444\",\"useDept\":\"123444\",\"mark\":\"123444\",\"contrackNo\":\"123444\",\"recDate\":\"2020-08-13\"},{\"checkId\":\"testId003\",\"checkYear\":\"123444\",\"balanYear\":\"123444\",\"reviceNo\":\"123444\",\"checkFlag\":\"123444\",\"checkAudFlag\":\"123444\",\"accept\":\"123444\",\"receivePay\":\"123444\",\"checkDate\":\"2020-08-13\",\"planNo\":\"123444\",\"sellName\":\"123444\",\"specs\":\"123444\",\"unit\":\"123444\",\"orderMoney\":\"123444\",\"sendAmount\":\"123444\",\"recAmount\":\"123444\",\"balAmount\":\"123444\",\"billMoney\":\"123444\",\"checkUnit\":\"123444\",\"useUnit\":\"123444\",\"useDept\":\"123444\",\"mark\":\"123444\",\"contrackNo\":\"123444\",\"recDate\":\"2020-08-13\"},{\"checkId\":\"testId004\",\"checkYear\":\"123444\",\"balanYear\":\"123444\",\"reviceNo\":\"123444\",\"checkFlag\":\"123444\",\"checkAudFlag\":\"123444\",\"accept\":\"123444\",\"receivePay\":\"123444\",\"checkDate\":\"2020-08-13\",\"planNo\":\"123444\",\"sellName\":\"123444\",\"specs\":\"123444\",\"unit\":\"123444\",\"orderMoney\":\"123444\",\"sendAmount\":\"123444\",\"recAmount\":\"123444\",\"balAmount\":\"123444\",\"billMoney\":\"123444\",\"checkUnit\":\"123444\",\"useUnit\":\"123444\",\"useDept\":\"123444\",\"mark\":\"123444\",\"contrackNo\":\"123444\",\"recDate\":\"2020-08-13\"},{\"checkId\":\"testId005\",\"checkYear\":\"123444\",\"balanYear\":\"123444\",\"reviceNo\":\"123444\",\"checkFlag\":\"123444\",\"checkAudFlag\":\"123444\",\"accept\":\"123444\",\"receivePay\":\"123444\",\"checkDate\":\"2020-08-13\",\"planNo\":\"123444\",\"sellName\":\"123444\",\"specs\":\"123444\",\"unit\":\"123444\",\"orderMoney\":\"123444\",\"sendAmount\":\"123444\",\"recAmount\":\"123444\",\"balAmount\":\"123444\",\"billMoney\":\"123444\",\"checkUnit\":\"123444\",\"useUnit\":\"123444\",\"useDept\":\"123444\",\"mark\":\"123444\",\"contrackNo\":\"123444\",\"recDate\":\"2020-08-13\"},{\"checkId\":\"testId006\",\"checkYear\":\"123444\",\"balanYear\":\"123444\",\"reviceNo\":\"123444\",\"checkFlag\":\"123444\",\"checkAudFlag\":\"123444\",\"accept\":\"123444\",\"receivePay\":\"123444\",\"checkDate\":\"2020-08-13\",\"planNo\":\"123444\",\"sellName\":\"123444\",\"specs\":\"123444\",\"unit\":\"123444\",\"orderMoney\":\"123444\",\"sendAmount\":\"123444\",\"recAmount\":\"123444\",\"balAmount\":\"123444\",\"billMoney\":\"123444\",\"checkUnit\":\"123444\",\"useUnit\":\"123444\",\"useDept\":\"123444\",\"mark\":\"123444\",\"contrackNo\":\"123444\",\"recDate\":\"2020-08-13\"},{\"checkId\":\"testId007\",\"checkYear\":\"123444\",\"balanYear\":\"123444\",\"reviceNo\":\"123444\",\"checkFlag\":\"123444\",\"checkAudFlag\":\"123444\",\"accept\":\"123444\",\"receivePay\":\"123444\",\"checkDate\":\"2020-08-13\",\"planNo\":\"123444\",\"sellName\":\"123444\",\"specs\":\"123444\",\"unit\":\"123444\",\"orderMoney\":\"123444\",\"sendAmount\":\"123444\",\"recAmount\":\"123444\",\"balAmount\":\"123444\",\"billMoney\":\"123444\",\"checkUnit\":\"123444\",\"useUnit\":\"123444\",\"useDept\":\"123444\",\"mark\":\"123444\",\"contrackNo\":\"123444\",\"recDate\":\"2020-08-13\"},{\"checkId\":\"testId008\",\"checkYear\":\"123444\",\"balanYear\":\"123444\",\"reviceNo\":\"123444\",\"checkFlag\":\"123444\",\"checkAudFlag\":\"123444\",\"accept\":\"123444\",\"receivePay\":\"123444\",\"checkDate\":\"2020-08-13\",\"planNo\":\"123444\",\"sellName\":\"123444\",\"specs\":\"123444\",\"unit\":\"123444\",\"orderMoney\":\"123444\",\"sendAmount\":\"123444\",\"recAmount\":\"123444\",\"balAmount\":\"123444\",\"billMoney\":\"123444\",\"checkUnit\":\"123444\",\"useUnit\":\"123444\",\"useDept\":\"123444\",\"mark\":\"123444\",\"contrackNo\":\"123444\",\"recDate\":\"2020-08-13\"},{\"checkId\":\"testId009\",\"checkYear\":\"123444\",\"balanYear\":\"123444\",\"reviceNo\":\"123444\",\"checkFlag\":\"123444\",\"checkAudFlag\":\"123444\",\"accept\":\"123444\",\"receivePay\":\"123444\",\"checkDate\":\"2020-08-13\",\"planNo\":\"123444\",\"sellName\":\"123444\",\"specs\":\"123444\",\"unit\":\"123444\",\"orderMoney\":\"123444\",\"sendAmount\":\"123444\",\"recAmount\":\"123444\",\"balAmount\":\"123444\",\"billMoney\":\"123444\",\"checkUnit\":\"123444\",\"useUnit\":\"123444\",\"useDept\":\"123444\",\"mark\":\"123444\",\"contrackNo\":\"123444\",\"recDate\":\"2020-08-13\"},{\"checkId\":\"testId010\",\"checkYear\":\"123444\",\"balanYear\":\"123444\",\"reviceNo\":\"123444\",\"checkFlag\":\"123444\",\"checkAudFlag\":\"123444\",\"accept\":\"123444\",\"receivePay\":\"123444\",\"checkDate\":\"2020-08-13\",\"planNo\":\"123444\",\"sellName\":\"123444\",\"specs\":\"123444\",\"unit\":\"123444\",\"orderMoney\":\"123444\",\"sendAmount\":\"123444\",\"recAmount\":\"123444\",\"balAmount\":\"123444\",\"billMoney\":\"123444\",\"checkUnit\":\"123444\",\"useUnit\":\"123444\",\"useDept\":\"123444\",\"mark\":\"123444\",\"contrackNo\":\"123444\",\"recDate\":\"2020-08-13\"}]},\"reason\":\"ok\",\"error_code\":0}";

        testData =
            "{\"result\":{\"total\":10,\"items\":[{\"checkId\":\"TestCheckId001\",\"accountRange\":\"2020-08-14\",\"settlementDate\":\"2020-08-14\",\"deliveryNum\":\"2020-08-14\",\"reconciliationSign\":\"2020-08-14\",\"assignableCenterSign\":\"2020-08-14\",\"receivingAudit\":\"2020-08-14\",\"receivingWay\":\"2020-08-14\",\"accountTime\":\"2020-08-14\",\"planNum\":\"2020-08-14\",\"goodsName\":\"2020-08-14\",\"specModel\":\"2020-08-14\",\"measurementUnit\":\"2020-08-14\",\"orderPrice\":\"100\",\"deliveryQuantity\":\"100\",\"receivedQuantity\":\"100\",\"settlementQuantity\":\"100\",\"receivedTotal\":\"100\",\"assignableDepName\":\"2020-08-14\",\"companyName\":\"2020-08-14\",\"depName\":\"2020-08-14\",\"assignableCause\":\"2020-08-14\",\"contractNum\":\"2020-08-14\",\"receiptDate\":\"2020-08-14\"},{\"checkId\":\"TestCheckId002\",\"accountRange\":\"2020-08-14\",\"settlementDate\":\"2020-08-14\",\"deliveryNum\":\"2020-08-14\",\"reconciliationSign\":\"2020-08-14\",\"assignableCenterSign\":\"2020-08-14\",\"receivingAudit\":\"2020-08-14\",\"receivingWay\":\"2020-08-14\",\"accountTime\":\"2020-08-14\",\"planNum\":\"2020-08-14\",\"goodsName\":\"2020-08-14\",\"specModel\":\"2020-08-14\",\"measurementUnit\":\"2020-08-14\",\"orderPrice\":\"100\",\"deliveryQuantity\":\"100\",\"receivedQuantity\":\"100\",\"settlementQuantity\":\"100\",\"receivedTotal\":\"100\",\"assignableDepName\":\"2020-08-14\",\"companyName\":\"2020-08-14\",\"depName\":\"2020-08-14\",\"assignableCause\":\"2020-08-14\",\"contractNum\":\"2020-08-14\",\"receiptDate\":\"2020-08-14\"},{\"checkId\":\"TestCheckId003\",\"accountRange\":\"2020-08-14\",\"settlementDate\":\"2020-08-14\",\"deliveryNum\":\"2020-08-14\",\"reconciliationSign\":\"2020-08-14\",\"assignableCenterSign\":\"2020-08-14\",\"receivingAudit\":\"2020-08-14\",\"receivingWay\":\"2020-08-14\",\"accountTime\":\"2020-08-14\",\"planNum\":\"2020-08-14\",\"goodsName\":\"2020-08-14\",\"specModel\":\"2020-08-14\",\"measurementUnit\":\"2020-08-14\",\"orderPrice\":\"100\",\"deliveryQuantity\":\"100\",\"receivedQuantity\":\"100\",\"settlementQuantity\":\"100\",\"receivedTotal\":\"100\",\"assignableDepName\":\"2020-08-14\",\"companyName\":\"2020-08-14\",\"depName\":\"2020-08-14\",\"assignableCause\":\"2020-08-14\",\"contractNum\":\"2020-08-14\",\"receiptDate\":\"2020-08-14\"},{\"checkId\":\"TestCheckId004\",\"accountRange\":\"2020-08-14\",\"settlementDate\":\"2020-08-14\",\"deliveryNum\":\"2020-08-14\",\"reconciliationSign\":\"2020-08-14\",\"assignableCenterSign\":\"2020-08-14\",\"receivingAudit\":\"2020-08-14\",\"receivingWay\":\"2020-08-14\",\"accountTime\":\"2020-08-14\",\"planNum\":\"2020-08-14\",\"goodsName\":\"2020-08-14\",\"specModel\":\"2020-08-14\",\"measurementUnit\":\"2020-08-14\",\"orderPrice\":\"100\",\"deliveryQuantity\":\"100\",\"receivedQuantity\":\"100\",\"settlementQuantity\":\"100\",\"receivedTotal\":\"100\",\"assignableDepName\":\"2020-08-14\",\"companyName\":\"2020-08-14\",\"depName\":\"2020-08-14\",\"assignableCause\":\"2020-08-14\",\"contractNum\":\"2020-08-14\",\"receiptDate\":\"2020-08-14\"},{\"checkId\":\"TestCheckId005\",\"accountRange\":\"2020-08-14\",\"settlementDate\":\"2020-08-14\",\"deliveryNum\":\"2020-08-14\",\"reconciliationSign\":\"2020-08-14\",\"assignableCenterSign\":\"2020-08-14\",\"receivingAudit\":\"2020-08-14\",\"receivingWay\":\"2020-08-14\",\"accountTime\":\"2020-08-14\",\"planNum\":\"2020-08-14\",\"goodsName\":\"2020-08-14\",\"specModel\":\"2020-08-14\",\"measurementUnit\":\"2020-08-14\",\"orderPrice\":\"100\",\"deliveryQuantity\":\"100\",\"receivedQuantity\":\"100\",\"settlementQuantity\":\"100\",\"receivedTotal\":\"100\",\"assignableDepName\":\"2020-08-14\",\"companyName\":\"2020-08-14\",\"depName\":\"2020-08-14\",\"assignableCause\":\"2020-08-14\",\"contractNum\":\"2020-08-14\",\"receiptDate\":\"2020-08-14\"},{\"checkId\":\"TestCheckId006\",\"accountRange\":\"2020-08-14\",\"settlementDate\":\"2020-08-14\",\"deliveryNum\":\"2020-08-14\",\"reconciliationSign\":\"2020-08-14\",\"assignableCenterSign\":\"2020-08-14\",\"receivingAudit\":\"2020-08-14\",\"receivingWay\":\"2020-08-14\",\"accountTime\":\"2020-08-14\",\"planNum\":\"2020-08-14\",\"goodsName\":\"2020-08-14\",\"specModel\":\"2020-08-14\",\"measurementUnit\":\"2020-08-14\",\"orderPrice\":\"100\",\"deliveryQuantity\":\"100\",\"receivedQuantity\":\"100\",\"settlementQuantity\":\"100\",\"receivedTotal\":\"100\",\"assignableDepName\":\"2020-08-14\",\"companyName\":\"2020-08-14\",\"depName\":\"2020-08-14\",\"assignableCause\":\"2020-08-14\",\"contractNum\":\"2020-08-14\",\"receiptDate\":\"2020-08-14\"},{\"checkId\":\"TestCheckId007\",\"accountRange\":\"2020-08-14\",\"settlementDate\":\"2020-08-14\",\"deliveryNum\":\"2020-08-14\",\"reconciliationSign\":\"2020-08-14\",\"assignableCenterSign\":\"2020-08-14\",\"receivingAudit\":\"2020-08-14\",\"receivingWay\":\"2020-08-14\",\"accountTime\":\"2020-08-14\",\"planNum\":\"2020-08-14\",\"goodsName\":\"2020-08-14\",\"specModel\":\"2020-08-14\",\"measurementUnit\":\"2020-08-14\",\"orderPrice\":\"100\",\"deliveryQuantity\":\"100\",\"receivedQuantity\":\"100\",\"settlementQuantity\":\"100\",\"receivedTotal\":\"100\",\"assignableDepName\":\"2020-08-14\",\"companyName\":\"2020-08-14\",\"depName\":\"2020-08-14\",\"assignableCause\":\"2020-08-14\",\"contractNum\":\"2020-08-14\",\"receiptDate\":\"2020-08-14\"},{\"checkId\":\"TestCheckId008\",\"accountRange\":\"2020-08-14\",\"settlementDate\":\"2020-08-14\",\"deliveryNum\":\"2020-08-14\",\"reconciliationSign\":\"2020-08-14\",\"assignableCenterSign\":\"2020-08-14\",\"receivingAudit\":\"2020-08-14\",\"receivingWay\":\"2020-08-14\",\"accountTime\":\"2020-08-14\",\"planNum\":\"2020-08-14\",\"goodsName\":\"2020-08-14\",\"specModel\":\"2020-08-14\",\"measurementUnit\":\"2020-08-14\",\"orderPrice\":\"100\",\"deliveryQuantity\":\"100\",\"receivedQuantity\":\"100\",\"settlementQuantity\":\"100\",\"receivedTotal\":\"100\",\"assignableDepName\":\"2020-08-14\",\"companyName\":\"2020-08-14\",\"depName\":\"2020-08-14\",\"assignableCause\":\"2020-08-14\",\"contractNum\":\"2020-08-14\",\"receiptDate\":\"2020-08-14\"},{\"checkId\":\"TestCheckId009\",\"accountRange\":\"2020-08-14\",\"settlementDate\":\"2020-08-14\",\"deliveryNum\":\"2020-08-14\",\"reconciliationSign\":\"2020-08-14\",\"assignableCenterSign\":\"2020-08-14\",\"receivingAudit\":\"2020-08-14\",\"receivingWay\":\"2020-08-14\",\"accountTime\":\"2020-08-14\",\"planNum\":\"2020-08-14\",\"goodsName\":\"2020-08-14\",\"specModel\":\"2020-08-14\",\"measurementUnit\":\"2020-08-14\",\"orderPrice\":\"100\",\"deliveryQuantity\":\"100\",\"receivedQuantity\":\"100\",\"settlementQuantity\":\"100\",\"receivedTotal\":\"100\",\"assignableDepName\":\"2020-08-14\",\"companyName\":\"2020-08-14\",\"depName\":\"2020-08-14\",\"assignableCause\":\"2020-08-14\",\"contractNum\":\"2020-08-14\",\"receiptDate\":\"2020-08-14\"},{\"checkId\":\"TestCheckId010\",\"accountRange\":\"2020-08-14\",\"settlementDate\":\"2020-08-14\",\"deliveryNum\":\"2020-08-14\",\"reconciliationSign\":\"2020-08-14\",\"assignableCenterSign\":\"2020-08-14\",\"receivingAudit\":\"2020-08-14\",\"receivingWay\":\"2020-08-14\",\"accountTime\":\"2020-08-14\",\"planNum\":\"2020-08-14\",\"goodsName\":\"2020-08-14\",\"specModel\":\"2020-08-14\",\"measurementUnit\":\"2020-08-14\",\"orderPrice\":\"100\",\"deliveryQuantity\":\"100\",\"receivedQuantity\":\"100\",\"settlementQuantity\":\"100\",\"receivedTotal\":\"100\",\"assignableDepName\":\"2020-08-14\",\"companyName\":\"2020-08-14\",\"depName\":\"2020-08-14\",\"assignableCause\":\"2020-08-14\",\"contractNum\":\"2020-08-14\",\"receiptDate\":\"2020-08-14\"}]},\"reason\":\"ok\",\"error_code\":0}";
        JSONObject apiResult = JSONObject.parseObject(testData);
        return apiResult;
    }

    /**
     * 查询对账单信息
     *
     * @param req 获取订单、对账单数据请求信息
     * @return 对账单信息列表
     * @author liulx
     * @date 2020-08-13 20:40:38
     */
    @Transactional(rollbackFor = Exception.class)
    public PurchaseReconciliationDTO listReconciliation(PurchaseReq req) {
        // Add By liwq On 2021-01-27 Start
        // 增加排序功能&指定字段排序功能
        if (!StringUtils.isEmpty(req.getSortField()) && StringUtils.isEmpty(req.getSortOrder())) {
            throw new BusinessException("请上送排序方式", "DAGM0001");
        }
        if (StringUtils.isEmpty(req.getSortField()) && !StringUtils.isEmpty(req.getSortOrder())) {
            throw new BusinessException("请上送排序字段", "DAGM0002");
        }
        if (!StringUtils.isEmpty(req.getSortOrder())) {
            List<String> sortOrders = mainBusinessConfig.getSortOrder();
            if (!sortOrders.contains(req.getSortOrder())) {
                throw new BusinessException("请上送有效排序方式", "DAGM0005");
            }
        }
        if (!StringUtils.isEmpty(req.getSortField())) {
            List<String> dagangSortField = mainBusinessConfig.getPurchaseReconciliationSortField();
            if (dagangSortField.size() == 0) {
                throw new BusinessException("请联系管理员维护采购中心有效排序字段", "DAGM0004");
            }
            if (dagangSortField.size() > 0) {
                if (!dagangSortField.contains(req.getSortField())) {
                    throw new BusinessException("请上送有效排序字段", "DAGM0003");
                }
            }
        }
        // Add By liwq On 2021-01-27 End

        Map<String, Object> params = new HashMap<>(4);
        // 请求采购中心对账单查询服务参数
        // params.put("accountnum", ACCOUNT_NUM);
        params.put("accountnum", mainBusinessConfig.getPurchaseAccount());
        params.put("companyname", req.getUserName());
        params.put("querytype", ReqTypeEnum.REQ_BILL_TYPE.getType());
        params.put("datefromto", req.getStartorenddate());
        if (StringUtils.isNotEmpty(req.getPlanNum())) {
            params.put("plancode", req.getPlanNum());
        }

        // Add By Liwq On 2021-01-27 Start
        // 增加排序功能&指定字段排序功能
        if (!StringUtils.isEmpty(req.getSortField()) && !StringUtils.isEmpty(req.getSortOrder())) {
            params.put("sortField", req.getSortField());
            params.put("sortOrder", req.getSortOrder());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getPageNum()))) {
            params.put("pageNum", req.getPagerInfo().getPageNum());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getPageSize()))) {
            params.put("pageSize", req.getPagerInfo().getPageSize());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getTotal()))) {
            params.put("total", req.getPagerInfo().getTotal());
        }
        // Add By Liwq On 2021-01-27 End

        JSONObject apiResult = apiUtil.sendApiLog(ReqTypeEnum.REQ_BILL_TYPE.getCode(), config.getPurchaseUrl(),
            getHeadMap(), params, HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
        // JSONObject apiResult = testReconciliationsData();
        String code = apiResult.getString("error_code");
        String message = apiResult.getString("reason");
        if (!SUCCESS.equals(code)) {
            throw new BusinessException(message, code);
        }
        PurchaseReconciliationDTO dto = new PurchaseReconciliationDTO();
        JSONObject result = apiResult.getJSONObject("result");
        Integer total = result.getInteger("total");

        // Add By Liwq On 2021-01-27 Start
        // 总条数
        req.getPagerInfo().setTotal(total);
        // Add By Liwq On 2021-01-27 End

        if (total == 0) {
            dto.setItems(Collections.emptyList());
            dto.setTotal(0);
            return dto;
        }
        JSONArray items = result.getJSONArray("items");
        // 转换数据
        List<PurchaserReconciliationRespBean> list = items.toJavaList(PurchaserReconciliationRespBean.class);
        dto.setTotal(total);
        dto.setItems(processRespListData(list, req));
        return dto;
    }

    /**
     * <pre>
     *      处理接口最新返回的数据，并将数据插入历史表中。
     *      针对最新数据处理方式：根据数据中每个业务 id 号，判断是否已经存在于数据库中
     *      如果已存在数据库，则将数据库中的数据更新为最新的数据;
     *      若不存在数据库中，则新增
     * </pre>
     *
     * @param beanList 接口返回最新对账单信息
     * @param req 基础请求对象，用于获取请求渠道、操作人等信息
     * @return 对账单数据传输集合
     * @author liulx
     * @date 2020-08-13 20:40:25
     */
    @Transactional(rollbackFor = Exception.class)
    protected List<ReconciliationDTO> processRespListData(List<PurchaserReconciliationRespBean> beanList,
        BaseReqObj req) {
        List<PurchaserReconciliationResp> list = beanList.stream().map(bean -> {
            PurchaserReconciliationResp resp = mapper.map(bean, PurchaserReconciliationResp.class);
            resp.setReconciliationId(bean.getId());
            return resp;
        }).collect(Collectors.toList());
        List<ReconciliationDTO> dtoList = new ArrayList<>(list.size());
        // 业务注解 id 缓存
        List<String> checkIds = new ArrayList<>();
        // 待保存的历史数据信息
        List<PurchaserReconciliationRespHistory> historyList = new ArrayList<>(list.size());
        list.forEach(obj -> {
            // 设置共用字段属性
            PurchaserReconciliationResp tempObj = BeanUtil.setGenericInfo(obj, req);
            // 转换成历史信息，并添加到历史信息集合中
            PurchaserReconciliationRespHistory history = mapper.map(tempObj, PurchaserReconciliationRespHistory.class);
            historyList.add(history);
            // 添加业务主键 id 到集合
            checkIds.add(obj.getReconciliationId());
            // 转换 DTO 并添加到集合中
            dtoList.add(transformReconciliationDTO(obj));
        });
        // 保存历史表
        reconciliationHistoryModel.saveBatch(historyList);
        LambdaQueryWrapper<PurchaserReconciliationResp> queryWrapper = new LambdaQueryWrapper<>();
        // 根据业务 id 查询返回数据列表中，已存在于数据库里的数据
        queryWrapper.in(PurchaserReconciliationResp::getReconciliationId, checkIds);
        // 数据库中已存在的数据
        List<PurchaserReconciliationResp> existList = reconciliationModel.list(queryWrapper);

        // 循环判断哪些数据需要更新，哪些是新增
        for (PurchaserReconciliationResp respObj : list) {
            for (PurchaserReconciliationResp existObj : existList) {
                // 找到已存在于数据库中的数据，说明需要更新该信息
                if (respObj.getReconciliationId().equals(existObj.getReconciliationId())) {
                    // 将已存在的数据 id，设置到新的数据对象中，按照新的数据对象进行更新
                    respObj.setId(existObj.getId());
                    break;
                }
            }
        }
        // 保存或更新数据
        reconciliationModel.saveOrUpdateBatch(list);
        return dtoList;
    }

    /**
     * 对账单 entity 转 DTO
     *
     * @param resp entity 数据
     * @return DTO
     */
    protected ReconciliationDTO transformReconciliationDTO(PurchaserReconciliationResp resp) {
        ReconciliationDTO dto = new ReconciliationDTO();
        dto.setCheckId(resp.getReconciliationId());
        dto.setCheckYear(resp.getAccountRange());
        dto.setBalanYear(resp.getSettlementDate());
        dto.setReviceNo(resp.getDeliveryNum());
        dto.setCheckFlag(resp.getReconciliationSign());
        dto.setCheckAudFlag(resp.getAssignableCenterSign());
        dto.setAccept(resp.getReceivingAudit());
        dto.setReceivePay(resp.getReceivingWay());
        dto.setCheckDate(resp.getAccountTime());
        dto.setPlanNo(resp.getPlanNum());
        dto.setSellName(resp.getGoodsName());
        dto.setSpecs(resp.getSpecModel());
        dto.setUnit(resp.getMeasurementUnit());
        dto.setOrderMoney(resp.getOrderPrice().toString());
        dto.setSendAmount(resp.getDeliveryQuantity().toString());
        dto.setRecAmount(resp.getReceivedQuantity().toString());
        dto.setBalAmount(resp.getSettlementQuantity().toString());
        dto.setBillMoney(resp.getReceivedTotal());
        dto.setCheckUnit(resp.getAssignableDepName());
        dto.setUseUnit(resp.getCompanyName());
        dto.setUseDept(resp.getDepName());
        dto.setMark(resp.getAssignableCause());
        dto.setContrackNo(resp.getContractNum());
        dto.setRecDate(resp.getReceiptDate());
        return dto;
    }

    /**
     * @Description 获取发票信息
     * @Date 10:15 2020/8/14
     * @Param [req]请求信息
     * @return com.ynet.middleground.riskmanage.dto.PurchaseInfoDTO
     **/
    @Transactional(rollbackFor = Exception.class)
    public PurchaseInvoiceDTO getInvoiceData(PurchaseReq req) {
        // Add By liwq On 2021-01-27 Start
        // 增加排序功能&指定字段排序功能
        if (!StringUtils.isEmpty(req.getSortField()) && StringUtils.isEmpty(req.getSortOrder())) {
            throw new BusinessException("请上送排序方式", "DAGM0001");
        }
        if (StringUtils.isEmpty(req.getSortField()) && !StringUtils.isEmpty(req.getSortOrder())) {
            throw new BusinessException("请上送排序字段", "DAGM0002");
        }
        if (!StringUtils.isEmpty(req.getSortOrder())) {
            List<String> sortOrders = mainBusinessConfig.getSortOrder();
            if (!sortOrders.contains(req.getSortOrder())) {
                throw new BusinessException("请上送有效排序方式", "DAGM0005");
            }
        }
        if (!StringUtils.isEmpty(req.getSortField())) {
            List<String> dagangSortField = mainBusinessConfig.getPurchaseInvoiceSortField();
            if (dagangSortField.size() == 0) {
                throw new BusinessException("请联系管理员维护采购中心有效排序字段", "DAGM0004");
            }
            if (dagangSortField.size() > 0) {
                if (!dagangSortField.contains(req.getSortField())) {
                    throw new BusinessException("请上送有效排序字段", "DAGM0003");
                }
            }
        }
        // Add By liwq On 2021-01-27 End

        Map<String, Object> params = new HashMap<>(4);
        // 请求采购中心服务参数
        // params.put("accountnum", ACCOUNT_NUM);
        params.put("accountnum", mainBusinessConfig.getPurchaseAccount());
        params.put("companyname", req.getUserName());
        params.put("querytype", ReqTypeEnum.REQ_INVOICE_TYPE.getType());
        params.put("datefromto", req.getStartorenddate());
        if (StringUtils.isNotEmpty(req.getPlanNum())) {
            params.put("plancode", req.getPlanNum());
        }

        // Add By Liwq On 2021-01-27 Start
        // 增加排序功能&指定字段排序功能
        if (!StringUtils.isEmpty(req.getSortField()) && !StringUtils.isEmpty(req.getSortOrder())) {
            params.put("sortField", req.getSortField());
            params.put("sortOrder", req.getSortOrder());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getPageNum()))) {
            params.put("pageNum", req.getPagerInfo().getPageNum());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getPageSize()))) {
            params.put("pageSize", req.getPagerInfo().getPageSize());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getTotal()))) {
            params.put("total", req.getPagerInfo().getTotal());
        }
        // Add By Liwq On 2021-01-27 End

        JSONObject apiResult = apiUtil.sendApiLog(ReqTypeEnum.REQ_BILL_TYPE.getCode(), config.getPurchaseUrl(),
            getHeadMap(), params, HostConstants.HTTP_METHOD_POST, LOG_NAME, req);

        // JSONObject apiResult = testInvoiceData();
        String code = apiResult.getString("error_code");
        String message = apiResult.getString("reason");
        if (!SUCCESS.equals(code)) {
            throw new BusinessException(message, code);
        }
        JSONObject result = apiResult.getJSONObject("result");

        Integer total = result.getInteger("total");

        // Add By Liwq On 2021-01-27 Start
        // 总条数
        req.getPagerInfo().setTotal(total);
        // Add By Liwq On 2021-01-27 End

        JSONArray items = result.getJSONArray("items");

        PurchaseInvoiceDTO purchaseInvoiceDTO = new PurchaseInvoiceDTO();
        purchaseInvoiceDTO.setTotal(total);
        if (total == 0) {
            purchaseInvoiceDTO.setItems(Collections.emptyList());
            return purchaseInvoiceDTO;
        }
        List<PurchaseInvoiceInfo> purchaseInvoiceInfoList = insertOrUpdateInvoiceInfo(items, req);

        List<PurchaseInvoiceDataDTO> purchaseInvoiceDataDTOList = invoiceDataConvert(purchaseInvoiceInfoList);

        purchaseInvoiceDTO.setItems(purchaseInvoiceDataDTOList);

        return purchaseInvoiceDTO;
    }

    /**
     * 发票实体类转DTO对象
     **/
    private List<PurchaseInvoiceDataDTO> invoiceDataConvert(List<PurchaseInvoiceInfo> purchaseInvoiceInfoList) {
        List<PurchaseInvoiceDataDTO> purchaseInvoiceDataDTOList = new ArrayList<>();

        PurchaseInvoiceDataDTO purchaseInvoiceDataDTO = null;

        for (PurchaseInvoiceInfo invoiceInfo : purchaseInvoiceInfoList) {
            purchaseInvoiceDataDTO = new PurchaseInvoiceDataDTO();

            purchaseInvoiceDataDTO.setBillNo(invoiceInfo.getBillnum())
                .setKpDate(DateUtils.asDate(invoiceInfo.getBilltime())).setKpMoney(invoiceInfo.getBillmoney());

            purchaseInvoiceDataDTOList.add(purchaseInvoiceDataDTO);
        }

        return purchaseInvoiceDataDTOList;
    }

    /**
     * 发票信息入库操作
     **/
    @Transactional(rollbackFor = Exception.class)
    public List<PurchaseInvoiceInfo> insertOrUpdateInvoiceInfo(JSONArray items, PurchaseReq req) {
        List<PurchaseInvoiceInfo> purchaseInvoiceInfoList = items.toJavaList(PurchaseInvoiceInfo.class);

        for (PurchaseInvoiceInfo purchaseInvoiceInfo : purchaseInvoiceInfoList) {
            BeanUtil.setGenericInfo(purchaseInvoiceInfo, req);
        }

        List<PurchaseInvoiceHistoryInfo> purchaseInvoiceHistoryInfoList =
            items.toJavaList(PurchaseInvoiceHistoryInfo.class);

        // 获取返回数据中的发票后6位编号
        List<String> billNumList = new ArrayList<>();

        // 订单信息存入历史表
        for (PurchaseInvoiceHistoryInfo purchaseInvoiceHistoryInfo : purchaseInvoiceHistoryInfoList) {
            BeanUtil.setGenericInfo(purchaseInvoiceHistoryInfo, req);
            billNumList.add(purchaseInvoiceHistoryInfo.getBillnum());
        }
        purchaseInvoiceHistoryInfoMapper.saveBatch(purchaseInvoiceHistoryInfoList);

        // 查询发票表信息数据查询条件
        QueryWrapper<PurchaseInvoiceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("billnum", billNumList.toArray());

        // 根据发票后6位编号查询发票信息表数据
        List<PurchaseInvoiceInfo> purchaseInvoiceInfoOldList = purchaseInvoiceInfoMapper.list(queryWrapper);

        // 新增数据集合
        List<PurchaseInvoiceInfo> purchaseInvoiceInfoInsertList = new ArrayList<>();

        // 更新数据集合
        List<PurchaseInvoiceInfo> purchaseInvoiceInfoUpdateList = new ArrayList<>();

        // 判断发票信息是否存在，存在更新，不存在新增
        boolean flag = false;
        Integer id = 0;
        for (PurchaseInvoiceInfo purchaseInvoiceInfo : purchaseInvoiceInfoList) {
            for (PurchaseInvoiceInfo purchaseInvoiceOldInfo : purchaseInvoiceInfoOldList) {
                if (purchaseInvoiceInfo.getBillnum().equals(purchaseInvoiceOldInfo.getBillnum())) {
                    flag = true;
                    id = purchaseInvoiceOldInfo.getId();
                    break;
                }
            }
            if (flag == true) {// 存在
                purchaseInvoiceInfo.setId(id);
                purchaseInvoiceInfoUpdateList.add(purchaseInvoiceInfo);
            } else {// 不存在
                purchaseInvoiceInfoInsertList.add(purchaseInvoiceInfo);
            }
        }

        purchaseInvoiceInfoMapper.saveBatch(purchaseInvoiceInfoInsertList);

        if (purchaseInvoiceInfoUpdateList != null && purchaseInvoiceInfoUpdateList.size() != 0) {
            purchaseInvoiceInfoMapper.updateBatchById(purchaseInvoiceInfoUpdateList);
        }

        return purchaseInvoiceInfoList;
    }

    /**
     * @Description 根据计划编号获取订单信息、对账单信息、发票信息
     * @Date 10:17 2020/8/14
     * @Param [req]
     * @return com.ynet.middleground.riskmanage.dto.PurchaseInfoDTO
     * @ModifyBy liulx
     * @ModifyDate 2020-09-11 11:23:11
     **/
    @Transactional(rollbackFor = Exception.class)
    public PurchaseInfoDTO getAllData(PurchaseReq req) {
        PurchaseInfoDTO purchaseInfoDTO = new PurchaseInfoDTO();
        PurchaseInvoiceDTO invoiceData = getInvoiceData(req);
        purchaseInfoDTO.setInvoice(invoiceData);
        if (StringUtils.isNotEmpty(req.getPlanNum())) {
            PurchaseOrderDTO orderData = getOrderData(req);
            purchaseInfoDTO.setOrder(orderData);
            PurchaseReconciliationDTO reconciliationData = listReconciliation(req);
            purchaseInfoDTO.setBill(reconciliationData);
        }
        return purchaseInfoDTO;
    }

    /**
     * 订单测试数据
     * 
     * @return
     */
    public JSONObject testOrderData() {
        String testData =
            "{\"result\":{\"total\":2,\"items\":[{\"planPeriod\":\"12321\",\"planNum\":\"ZYB001\",\"supplierName\":\"1234567890\",\"goodsCode\":\"1234567890\",\"goodsName\":\"1234567890\",\"specModel\":\"1234567890\",\"remarks\":\"1234567890\",\"measurementUnit\":\"1234567890\",\"planQuantity\":1,\"orderQuantity\":2,\"acceptQuentity\":4,\"sellingPrice\":3,\"billTotal\":5,\"depName\":\"1234567890\",\"inquiryNum\":\"1234567890\",\"sureSign\":\"1234567890\",\"payWay\":\"1234567890\",\"orderStatus\":\"1234567890\",\"requiredDeliveryDate\":\"2020-08-14\",\"deliveryDate\":\"2020-08-14\",\"brandOrigin\":\"1234567890\",\"warrantyPeriod\":\"1234567890\",\"defectsPeriod\":\"1234567890\",\"qualityStandard\":\"1234567890\",\"deliveryRegion\":\"1234567890\",\"location\":\"1234567890\",\"applicant\":\"1234567890\",\"applicationDate\":\"2020-08-14\",\"projectNumber\":\"1234567890\",\"projectName\":\"1234567890\",\"planUse\":\"1234567890\",\"planWay\":\"1234567890\",\"targetSign\":\"1234567890\",\"contractNum\":\"1234567890\",\"goodsCategoryCode\":\"1234567890\",\"goodsCategoryName\":\"1234567890\",\"problemSign\":\"1234567890\",\"fixedAssets\":\"1234567890\",\"createTime\":\"2020-08-14 10:10:11\",\"buyer\":\"1234567890\",\"buyWay\":\"1234567890\",\"calibrationPerson\":\"1234567890\"},{\"planPeriod\":\"12321\",\"planNum\":\"ZYB002\",\"supplierName\":\"1234567890\",\"goodsCode\":\"1234567890\",\"goodsName\":\"1234567890\",\"specModel\":\"1234567890\",\"remarks\":\"1234567890\",\"measurementUnit\":\"1234567890\",\"planQuantity\":1,\"orderQuantity\":2,\"acceptQuentity\":4,\"sellingPrice\":3,\"billTotal\":5,\"depName\":\"1234567890\",\"inquiryNum\":\"1234567890\",\"sureSign\":\"1234567890\",\"payWay\":\"1234567890\",\"orderStatus\":\"1234567890\",\"requiredDeliveryDate\":\"2020-08-14\",\"deliveryDate\":\"2020-08-14\",\"brandOrigin\":\"1234567890\",\"warrantyPeriod\":\"1234567890\",\"defectsPeriod\":\"1234567890\",\"qualityStandard\":\"1234567890\",\"deliveryRegion\":\"1234567890\",\"location\":\"1234567890\",\"applicant\":\"1234567890\",\"applicationDate\":\"2020-08-14\",\"projectNumber\":\"1234567890\",\"projectName\":\"1234567890\",\"planUse\":\"1234567890\",\"planWay\":\"1234567890\",\"targetSign\":\"1234567890\",\"contractNum\":\"1234567890\",\"goodsCategoryCode\":\"1234567890\",\"goodsCategoryName\":\"1234567890\",\"problemSign\":\"1234567890\",\"fixedAssets\":\"1234567890\",\"createTime\":\"2020-08-14 10:10:11\",\"buyer\":\"1234567890\",\"buyWay\":\"1234567890\",\"calibrationPerson\":\"1234567890\"}]},\"reason\":\"ok\",\"error_code\":0}";
        JSONObject apiResult = JSONObject.parseObject(testData);
        return apiResult;
    }

    /**
     * 发票测试数据
     * 
     * @return
     */
    public JSONObject testInvoiceData() {
        String testData =
            "{\"result\":{\"total\":3,\"items\":[{\"billnum\":\"123456\",\"billtime\":\"2020-10-18\",\"billmoney\":100},{\"billnum\":\"345678\",\"billtime\":\"2020-10-18\",\"billmoney\":100},{\"billnum\":\"234567\",\"billtime\":\"2020-10-18\",\"billmoney\":100}]},\"reason\":\"ok\",\"error_code\":0}";
        JSONObject apiResult = JSONObject.parseObject(testData);
        return apiResult;
    }

}
